package com.sharemarking.wa.platform.service.OrderDelayQueue;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.Order;
import com.sharemarking.wa.common.entity.OrderAddress;
import com.sharemarking.wa.common.entity.OrderDetails;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.platform.mapper.OrderAddressMapper;
import com.sharemarking.wa.platform.mapper.OrderDetailMapper;
import com.sharemarking.wa.platform.mapper.OrderMapper;
import com.sharemarking.wa.platform.payconfig.OrderQueryService;
import com.sharemarking.wa.platform.service.JGPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author dxy
 */
@Service
public class OrderConsumer {
    @Autowired
    private OrderQueue orderQueue;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private OrderQueryService queryService;
    @Autowired
    private JGPushService jgPushService;
    //创建一个线程，监听订单队列
    //当每个订单超过规定时间后未支付，则删除相关数据
    @PostConstruct
    public void initThread() {
        //在这里开启线程，执行操作
        ChildThread ct = new ChildThread();
        ct.setName("orderDelayQueue-Thread");
        ct.setDaemon(true);
        ct.start();
    }

    //内部类
    private class ChildThread extends Thread {
        @Override
        public void run() {
            while (true) {
                OrderDelay take = null;
                try {
                    take = orderQueue.getQueue().take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dealOrder(take.getId());
            }
        }
    }


    @Async("orderDelayQueue")
    public void dealOrder(Integer id){
        Order order = orderMapper.selectById(id);
        String messageStr = "您好，尾号为"+order.getCode().substring(order.getCode().length() - 10)+"的子订单由于长时间没有支付，已取消";
        jgPushService.pushTag(messageStr,order.getSendOrgMemberId());

        //如果超时未支付，进行删除订单的操作
        int col = orderMapper.delete(new QueryWrapper<Order>().eq("id", id).eq("state", 4));
        if (col != 0) {
            //继续删除子单的相关内容
            orderDetailMapper.delete(new QueryWrapper<OrderDetails>().eq("order_id", id));
            //删除order_address相关内容
            orderAddressMapper.delete(new QueryWrapper<OrderAddress>().eq("order_id",id));
        }
    }
}
